﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ayxjDllClass
{
    public static class ConvertExtensions
    {
        public static byte[] HexStringToByteArray(this string hex)
        {
            int length = hex.Length;
            byte[] bytes = new byte[length / 2]; // 每两个字符表示一个字节

            for (int i = 0; i < length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }

            return bytes;
        }

        public static byte ToByte(this string hex)
        {
            hex = hex.Replace(" ", "");
            return Convert.ToByte("0x" + hex, 16);
        }

        public static UInt32 ToUInt32(this string hex)
        {
            hex = hex.Replace(" ", "");
            return Convert.ToUInt32("0x" + hex, 16);
        }

        public static byte[] FromInt32(this int data, bool bigEndian = false)
        {
            byte[] bytes = BitConverter.GetBytes(data);
            if (bigEndian)
                Array.Reverse(bytes);
            return bytes;
        }

        static byte[] CopyBytes(this byte[] bytes, int index, int len, bool reverse = false)
        {
            byte[] bytesdest = new byte[len];
            Array.Copy(bytes, index, bytesdest, 0, bytesdest.Length);
            if (reverse)
               return bytesdest.Reverse().ToArray();
            return bytesdest;
        }

        public static Int32 ToInt32(this byte[] bytes, int index, bool littleEndian = true)
        {
            if (BitConverter.IsLittleEndian ^ littleEndian)
            {
                byte[] bytesdest = bytes.CopyBytes(index, 4, true);
                return BitConverter.ToInt32(bytesdest, 0);
            }
            return BitConverter.ToInt32(bytes, index);
        }

        public static Int16 ToInt16(this byte[] bytes, int index, bool littleEndian = true)
        {
            if (BitConverter.IsLittleEndian ^ littleEndian)
            {
                byte[] bytesdest = bytes.CopyBytes(index, 2, true);
                return BitConverter.ToInt16(bytesdest, 0);
            }
            return BitConverter.ToInt16(bytes, index);
        }
    }
}
